/**
 * Created by Administrator on 2018/7/19.
 */
import Vue from 'vue'
import { Message } from 'element-ui';
import axios from 'axios'
import global_ from '../components/Global'
let upload=async function (id){
  var client;

  let postA=async function(){
    var res;
    try {
      res = await axios.post(global_.$baseUrl + "/admin/file/getStsToken")
    } catch (e) {
      console.log(e);
    }
     console.log(res);
   client = new OSS.Wrapper({
     region: res.data.data.endpoint.split('.')[0],
     secure: true,
     accessKeyId: res.data.data.accessKeyId,
     /*这两者到阿里云控制台获得*/
     stsToken: res.data.data.securityToken,
     accessKeySecret: res.data.data.accessKeySecret,
     bucket: res.data.data.bucketName/*装图片的桶名*/
   });
   var files = document.getElementById(id);
   if (files.files) {
     var fileLen = document.getElementById(id).files
     for (var i = 0; i < fileLen.length; i++) {
       var file = fileLen[i];
       // 随机命名
       var random_name = random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop();
       async function multipartUpload () {
         try {
           let result = await client.multipartUpload(random_name, file, {
             progress: async function (p) {
             console.log('Progress: ' + p);
           },
           meta: {
             year: 2017,
               people: 'test'
           },
           mime: 'image/jpeg'
         });
         console.log(result);
         return result;
       } catch (e) {
         Message.error('请求错误')
         console.log(e);

       }
     }
     return await multipartUpload()
   }
  }
 }
let getSomething = async function(){
  let a = await postA();
  return a;
}
 return await getSomething();
 }
// 随机生成文件名
function random_string(len) {
  len = len || 32;
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  var maxPos = chars.length;
  var pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
};

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

function getRsa(modulus,exponent,pass) {
  var rsaKey = new RSAKey();
  rsaKey.setPublic(b64tohex(modulus), b64tohex(exponent));
  var password=hex2b64(rsaKey.encrypt(pass));
  return password;
};
export default{
  formatDate,
  getRsa,
  upload
  }
